<template>
  <div class="home">
    <!-- 欢迎标题 -->
    <div class="welcome-section">
      <h2>🍊 欢迎回来，{{ username }}</h2>
    </div>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">项目数</div>
          <div class="stat-value">{{ stats.totalProjects }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">新添预算</div>
          <div class="stat-value">{{ stats.totalBudget }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">剩余人力</div>
          <div class="stat-value">{{ stats.totalManpower }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">任务数</div>
          <div class="stat-value">{{ stats.totalTasks }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <!-- 饼状图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <div class="chart-title">项目进度概览（饼状图）</div>
            <div id="pie-chart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 柱状图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <div class="chart-title">项目进度概览（柱状图）</div>
            <div id="bar-chart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, reactive } from 'vue';
import axios from 'axios';

// 动态获取用户名
const username = localStorage.getItem('username') || '游客'; // 如果没有用户名，显示“游客”

// 统计数据
const stats = reactive({
  totalProjects: 0,
  totalBudget: 0,
  totalManpower: 0,
  totalTasks: 0,
  pieChartData: [], // 饼状图数据
  barChartData: {
    xAxis: [], // 柱状图的 X 轴数据
    series: [], // 柱状图的系列数据
  },
});

// 获取统计卡片数据
const fetchStats = async () => {
  const token = localStorage.getItem('token'); // 从本地存储中获取 token
  if (!token) {
    console.error('Token 不存在，无法发送请求');
    return;
  }
  try {
    const response = await axios.get('http://localhost:8080/project/overview', {
      headers: {
        Authorization: `Bearer ${token}`, // 在请求头中携带 token
      },
    });
    const data = response.data.data;
    if (!data) {
      throw new Error('后端返回的数据结构不正确，data 为 undefined');
    }
    stats.totalProjects = data.totalProjects || 0;
    stats.totalBudget = data.totalBudget || 0;
    stats.totalManpower = data.totalManpower || 0;
    stats.totalTasks = data.totalTasks || 0;
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};

// 获取饼状图数据
const fetchPieChartStats = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    console.error('Token 不存在，无法发送请求');
    return;
  }
  try {
    const response = await axios.get('http://localhost:8080/progress/project/stats', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    const data = response.data.data;
    if (!data || !Array.isArray(data)) {
      throw new Error('饼状图后端返回的数据结构不正确，data 应为数组');
    }
    stats.pieChartData = data.map(item => ({
      value: item.value,
      name: item.name,
    }));
    updatePieChart();
  } catch (error) {
    console.error('获取饼状图数据失败:', error);
  }
};

// 获取柱状图数据
const fetchBarChartStats = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    console.error('Token 不存在，无法发送请求');
    return;
  }
  try {
    const response = await axios.get('http://localhost:8080/task/stats/status', {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    const data = response.data.data;
    if (!data || !data.xAxis || !data.series) {
      throw new Error('柱状图后端返回的数据结构不正确');
    }
    stats.barChartData.xAxis = data.xAxis;
    stats.barChartData.series = data.series;
    updateBarChart();
  } catch (error) {
    console.error('获取柱状图数据失败:', error);
  }
};

// 更新饼状图
const updatePieChart = () => {
  const pieChartDom = document.getElementById('pie-chart');
  const pieChart = echarts.init(pieChartDom);
  const pieOption = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      bottom: '10%',
    },
    series: [
      {
        name: '项目进度',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: stats.pieChartData,
      },
    ],
  };
  pieChart.setOption(pieOption);
};

// 更新柱状图
const updateBarChart = () => {
  const barChartDom = document.getElementById('bar-chart');
  const barChart = echarts.init(barChartDom);
  const barOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    xAxis: {
      type: 'category',
      data: stats.barChartData.xAxis,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '任务状态',
        type: 'bar',
        data: stats.barChartData.series,
        itemStyle: {
          color: '#5470C6',
        },
      },
    ],
  };
  barChart.setOption(barOption);
};

// 页面加载时获取数据并初始化图表
onMounted(() => {
  fetchStats();
  fetchPieChartStats();
  fetchBarChartStats();
});
</script>

<style scoped>
.home {
  padding: 20px;
  background-color: #f5f5f5;
}

.welcome-section {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 16px;
  color: #888;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.chart-section {
  margin-top: 20px;
}

.chart-card {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
}
</style>